﻿using aier.dataaccess.dapper;
using aier.dataaccess.model;
using aier.xrm.wcf;
using log4net;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aier.business.logic
{
    public class DoctorBll
    {
        public DoctorDal doctorDal { get; set; }
        public ILog log { get; set; }
        public ResResult resResult { get; set; }
        public CommonWcf commonWcf { get; set; }
        public ChineseToLetterBll toLetterBll { get; set; }

        /// <summary>
        /// 修改医生
        /// </summary>
        /// <param name="contactInfo"></param>
        /// <returns></returns>
        public ResResult ModDoctor(ContactInfo contactInfo)
        {
            try
            {
                if (contactInfo == null)
                {
                    log.Error("ModDoctor 出现错误：传入实体为空");
                    return resResult.FailResult("DoctorBll ->ModDoctor : 传入实体为空");
                }
               // contactInfo.New_type = 1;
                Entity entity = contactInfo.AsCrmEntity();
                if (contactInfo.userid == Guid.Empty)
                {
                      commonWcf.UpdateEntityById(entity);
                }
                else
                {
                   commonWcf.UpdateEntityProxyById(contactInfo.userid, entity);
                }

                return resResult.SuccessResult(contactInfo.Contactid);
            }
            catch (Exception e)
            {
                log.Error("AddDoctor 出现错误：" + e.Message);
                return resResult.FailResult("DoctorBll ->ModDoctor Error:" + e.Message);

            }

        }

        /// <summary>
        /// 添加医生
        /// </summary>
        /// <param name="contactInfo"></param>
        /// <returns></returns>
        public ResResult AddDoctor(ContactInfo contactInfo)
        {
            Guid resultId = Guid.Empty;
            try
            {
                if (contactInfo == null)
                {
                    log.Error("AddDoctor 出现错误：传入实体为空");
                    return resResult.FailResult("DoctorBll ->AddDoctor : 传入实体为空");
                }
                //contactInfo.New_type = 1;
                Entity entity = contactInfo.AsCrmEntity();
                if (contactInfo.userid == Guid.Empty)
                {
                    resultId = commonWcf.CreateEntity(entity);
                }
                else
                {
                    resultId = commonWcf.CreateEntityProxy(contactInfo.userid, entity);
                }

                return resResult.SuccessResult(resultId);
            }
            catch (Exception e)
            {
                log.Error("AddDoctor 出现错误：" + e.Message);
                return resResult.FailResult("DoctorBll ->AddDoctor Error:" + e.Message);

            }

        }

        /// <summary>
        /// 获取全部医生
        /// </summary>
        /// </param>
        /// <returns></returns>
        public PageResult<GroupResult<ContactView>> QryDoctorList(Guid ownerid)
        {
            PageResult<GroupResult<ContactView>> pageResult = new PageResult<GroupResult<ContactView>>();
            List<ContactView> doctorList =  doctorDal.QryDoctorList(null, ownerid, Guid.Empty,false).ToList();
            int total = doctorDal.QryDoctorListCountByConditions(null, ownerid, Guid.Empty, false,null,null,null,string.Empty);
            List<GroupResult<ContactView>> groupResults = GroupData(doctorList);
            pageResult.datas = groupResults;
            pageResult.total = total;
            pageResult.existsnextdata = total > 500;
            return pageResult;
        }

        /// <summary>
        /// 根据条件获取全部医生
        /// </summary>
        /// </param>
        /// <returns></returns>
        public List<GroupResult<ContactView>> QryDoctorListByConditions(string liveness,Guid ownerid,Guid district,bool isml)
        {
            List<ContactView> doctorList = doctorDal.QryDoctorList(liveness, ownerid, district,isml).ToList();
            List<GroupResult<ContactView>> groupResults = GroupData(doctorList);
            return groupResults;
        }

        /// <summary>
        /// 学术推广首页点击查看详情进入
        /// </summary>
        /// <param name="liveness"></param>
        /// <param name="ownerid"></param>
        /// <param name="district"></param>
        /// <param name="isml"></param>
        /// <param name="startTime"></param>
        /// <param name="endDate"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public PageResult<GroupResult<ContactView>> QryDoctorListByConditions(string liveness, Guid ownerid, Guid district, bool isml,DateTime startTime,DateTime endDate,int type,string doctorname)
        {
            PageResult<GroupResult<ContactView>> pageResult = new PageResult<GroupResult<ContactView>>();
            List<ContactView> doctorList = doctorDal.QryDoctorList(liveness, ownerid, district, isml,startTime,endDate,type,doctorname).ToList();
            int total = doctorDal.QryDoctorListCountByConditions(liveness, ownerid, district, isml, startTime, endDate, type, doctorname);
            List<GroupResult<ContactView>> groupResults = GroupData(doctorList);
            pageResult.datas = groupResults;
            pageResult.total = total;
            pageResult.existsnextdata = total > 500;
            return pageResult;
        }


        /// <summary>
        ///获取区域
        /// </summary>
        /// </param>
        /// <returns></returns>
        public IEnumerable<ContactView> QryAreaByConditions( Guid ownerid) {
            return doctorDal.QryAreaByConditions(ownerid);
        }

        /// <summary>
        /// 根据id获取医生
        /// </summary>
        /// </param>
        /// <returns></returns>
        public ContactView QryDoctorById(Guid doctorid)
        {
            return doctorDal.QryDoctorById(doctorid);
        }


        /// <summary>
        /// 对数据根据首字母分组
        /// </summary>
        /// <param name="recommendViews"></param>
        /// <returns></returns>
        private List<GroupResult<ContactView>> GroupData(List<ContactView> doctorList)
        {
            var dicResult = doctorList.Where(t => !string.IsNullOrWhiteSpace(t.LastName))
                                      .GroupBy(t => toLetterBll.startWithFirst(t.LastName[0]))
                                      .ToDictionary(t => t.Key, t => t.ToList());

            var doctorListnull = doctorList.Where(t => string.IsNullOrWhiteSpace(t.LastName));
            Dictionary<string, List<ContactView>> dicResultnull =null;
            if (doctorListnull.ToList().Count > 0)
            {
                dicResultnull = new Dictionary<string, List<ContactView>>();
                dicResultnull.Add("#", doctorListnull.ToList());
                dicResult = dicResult.OrderBy(t => t.Key).Concat(dicResultnull).ToDictionary(k => k.Key, v => v.Value);
            }
            else {
                dicResult = dicResult.OrderBy(t => t.Key).ToDictionary(k => k.Key, v => v.Value);
            }

          

            var groupResults = dicResult.ToList().Select(item =>
            {
                GroupResult<ContactView> groupResult = new GroupResult<ContactView>();
                groupResult.groupname = item.Key;
                groupResult.grouplist = item.Value;
                return groupResult;
            })?.ToList();

            return groupResults;
        }
    }
}
